﻿/*综合文档管理
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jw.Web.App_Start;
using System.Web.Http;
using Jw.Core;
using Jw.Models;
using System.IO;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json;
using Jw.Web.Areas.Pacm.Common;
using Jw.Web.Areas.Qms.Common;

namespace Jw.Web.Areas.Qms.Controllers
{
    public class FileContentController : BaseController
    {
        //质量_文档管理
        // GET: /Qms/FileContent/
        public ActionResult Index(string id = "zl")
        {
            var isPublicItems = new List<dynamic>();
            isPublicItems.Add(new { value = 0, text = "不公开" });
            isPublicItems.Add(new { value = 1, text = "公开" });
            //passed
            var isApproveStateItems = new List<dynamic>();
            isApproveStateItems.Add(new { value = "passed", text = "已发布" });
            //isApproveStateItems.Add(new { value = "notpassed", text = "未发布" });
            var model = new
            {
                isTypeId = id, //文档类型
                idField = "FileContent_FileBh", //主键
                urls = QmsHelper.GetIndexUrls("FileContent"),
                resx = QmsHelper.GetIndexResx("文档管理"),
                dataSource = new
                {
                    userCode = QmsHelper.GetUserCode(), //向页面传递 用户Code 
                    publicItems = isPublicItems,//是否公开
                    ApproveStateItems = isApproveStateItems

                },
                form = new
                {
                    FileType_Lb = id, //文档数据类别
                    FileContent_ValidDate = "",//有效日期
                    FileContent_Title = "", //文档名
                    FileContent_IsPublic = "",//是否公开
                    ApproveState = "" //是否发布
                }
            };
            return View(model);
        }

        [MvcMenuFilter(false)]
        public ActionResult Edit(string id = "")
        {
            //解析文档编号和类型编号
            string[] arg = id.Split(';'); // 编号  +";" + 类别编号
            string sTypebh = "";
            id = arg[0];
            if (arg.Length == 2)
            {
                id = arg[0];
                sTypebh = arg[1];
            }
            var data = new FileContentApiController().GetEditMaster(id);
            var codeService = new sys_codeService();
            var isPublicItems = new List<dynamic>();
            isPublicItems.Add(new { value = 0, text = "不公开" });
            isPublicItems.Add(new { value = 1, text = "公开" });
            var model = new
            {
                form = data.form,
                scrollKeys = data.scrollKeys,
                urls = QmsHelper.GetEditUrls("FileContent"),
                resx = QmsHelper.GetEditResx("综合文档管理"),
                dataSource = new
                {
                    publicItems = isPublicItems //是否公开
                },
                defaultForm = new q_FileContent().Extend(new
                {
                    FileContent_FileBh = id,
                    FileContent_TypeBh = sTypebh,
                    FileContent_UserCode = QmsHelper.GetUserCode(), //接收人
                    FileContent_IsPublic = 1 //是否公开
                }),
                defaultRow = new
                {

                },
                setting = new
                {
                    postFormKeys = new string[] { "FileContent_FileBh" },
                }
            };
            return View(model);
        }

        /// <summary>
        /// 个人文档中心查询
        /// </summary>
        /// <returns></returns>
        public ActionResult FileUsersList(string id = "")
        {
            var model = new
            {
                idField = "FileContentUserId", //主键
                urls = new
                {
                    query = "/api/qms/FileContent/GetUserFileList/",
                    remove = "/api/qms/FileContent/DeleteUserFileList/"
                },
                resx = QmsHelper.GetIndexResx("个人文档中心"),
                dataSource = new
                {
                    yesnoItems = new sys_codeService().GetYesNoItems()
                },
                form = new
                {
                    FileType_Lb = id, //数据库类别 zl jh rb
                    IsRead = 0,
                    FileContent_Title = "", //文档名称
                    PublishUser = "",//发布人员
                    CreateTime = "", //发布日期
                    FileContent_ValidDate = "" //有效日期
                }

            };
            return View(model);

        }

        [MvcMenuFilter(false)]
        public ActionResult UpLoad(string id)
        {
            ViewBag.FileId = id;
            return View();
        }
        /// <summary>
        /// 下载指定的文件
        /// </summary>
        /// <param name="id"></param>
        [MvcMenuFilter(false)]
        public void DownLoad(string id)
        {
            //文件号|行号
            string sFilebh = id.Split('|')[0];
            string sRowId = id.Split('|')[1];
            q_FileAttachmentService service = new q_FileAttachmentService();
            q_FileAttachment obj = service.GetModel(new ParamQuery().AndWhere("FileAttachment_FileBh", sFilebh).AndWhere("FileAttachment_RowId", sRowId));
            string filePath = Server.MapPath("~/Upload/") + obj.FileAttachment_Path;
            Jw.Utils.ZFiles.DownloadFile(System.Web.HttpContext.Current, filePath, 1024102410);
        }

        /// <summary>
        /// 删除指定的文件
        /// </summary>
        /// <param name="id"></param>
        [MvcMenuFilter(false)]
        public ActionResult DeleteFile(string id)
        {
            string sFilebh = id.Split('|')[0];
            string sRowId = id.Split('|')[1];
            var mObj = new q_FileContentService().GetModel(new ParamQuery().AndWhere("FileContent_FileBh", sFilebh));
            if (mObj.ApproveState == null) mObj.ApproveState = "";
            if (mObj.ApproveState.Trim() == "passed")
            {
                return Json(new { success = false, message = "删除失败、该文档已经发布!" });
            }

            q_FileAttachmentService service = new q_FileAttachmentService();
            q_FileAttachment obj = service.GetModel(new ParamQuery().AndWhere("FileAttachment_FileBh", sFilebh).AndWhere("FileAttachment_RowId", sRowId));


            string filePath = Server.MapPath("~/Upload/") + obj.FileAttachment_Path;
            Jw.Utils.ZFiles.DeleteFiles(filePath);

            service.Delete(new ParamDelete().AndWhere("FileAttachment_FileBh", sFilebh).AndWhere("FileAttachment_RowId", sRowId));

            return Json(new { success = true, message = "" });
        }


    }

    //api/qms/Filecontent  
    public class FileContentApiController : ApiController
    {

        /// <summary>
        /// 删除个人文件记录
        /// </summary>
        /// <param name="id"></param>
        public void DeleteUserFileList(string id)
        {
            var result = new q_FileContentUsersService().Delete(new ParamDelete().AndWhere("FileContentUserId", id));
            PacmHelper.ThrowHttpExceptionWhen(result <= 0, "单据删除失败[FileContentUserId={0}]，请重试或联系管理员！", id);
        }
        /// <summary>
        /// 得到个人的接收的文档
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public dynamic GetUserFileList(RequestWrapper request)
        {
            request.LoadSettingXmlString(@"
            <settings defaultOrderBy='a.CreateTime Desc'>
            <select>
                a.*, b.FileContent_ValidDate ,b.FileContent_Title,c.FileAttachment_FileBh,c.FileAttachment_RowId,c.FileAttachment_FullName
            </select>
            <from>
                q_FileContentUsers  a 
                left outer join q_FileContent    b on b.FileContent_FileBh = a.FielContendId
                left outer join q_FileAttachment c on c.FileAttachment_FileBh = a.FielContendId
                left outer join q_fileType d on d.FileType_Bh = b.FileContent_TypeBh
            </from>
             <where defaultForAll='true' defaultCp='equal' defaultIgnoreEmpty='true' >
                <field name='d.FileType_Lb'              cp='equal' ignoreEmpty='true'    ></field>
                <field name='a.CreateTime'              cp='daterange' ignoreEmpty='true'    ></field>
                <field name='b.FileContent_ValidDate'   cp='daterange' ignoreEmpty='true'   ></field>
                <field name='b.FileContent_Title'       cp='like' ignoreEmpty='true'></field>
            </where>
            </settings>");
            ParamQuery query = request.ToParamQuery();
            //加权限
            if (QmsHelper.GetUserCode() != "super") query = query.AndWhere("a.UserCode", QmsHelper.GetUserCode());
            var service = new q_FileContentUsersService();
            var result = service.GetDynamicListWithPaging(query);
            return result;

        }

        /// <summary>
        /// 是否阅读的处理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void UserFileListRead(string id)
        {
            var UsersService = new q_FileContentUsersService();
            var obj = UsersService.GetModel(new ParamQuery().AndWhere("FileContentUserId", id));


            var result = UsersService.Update(new ParamUpdate().Column("IsRead", 1).Column("ReadCount", obj.ReadCount + 1).AndWhere("FileContentUserId", id));
            PacmHelper.ThrowHttpExceptionWhen(result <= 0, "单据删除失败[FileContentUserId={0}]，请重试或联系管理员！", id);
        }

        /// <summary>
        /// 得到列表页面
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public dynamic Get(RequestWrapper request)
        {
            request.LoadSettingXmlString(@"
            <settings defaultOrderBy='CreateDate Desc'>
            <select>
                case  isnull(ApproveState,'') when 'passed' then 'passed' else 'notpassed' end ApproveState,FileContent_FileBh,FileContent_TypeBh,FileContent_Title,CreatePerson,CreateDate,FileContent_Bmbh,FileContent_Bmmc,FileContent_UserCode,FileContent_IsPublic,FileContent_ValidDate,
                IsNull((select convert(varchar(10),FileAttachment_RowId) +'|'+ FileAttachment_FullName+'*'   from q_FileAttachment where FileAttachment_FileBh = q_FileContent.FileContent_FileBh  for xml path('')),'0') as FileContent_Fjsl 
            </select>
            <from>
                dbo.q_FileContent left outer join  dbo.q_FileType on FileType_Bh =  FileContent_TypeBh
            </from>
             <where defaultForAll='true' defaultCp='equal' defaultIgnoreEmpty='true' >
                <field name='FileType_Lb'  cp='equal'  ignoreEmpty='true'></field>
                <field name='FileContent_TypeBh' cp='equal' ignoreEmpty='true'></field>
                <field name='FileContent_Title'  cp='like'  ignoreEmpty='true'></field>
                <field name='FileContent_Title'  cp='like'  ignoreEmpty='true'></field>
            </where>
            </settings>");
            var service = new q_FileContentService();
            ParamQuery query = request.ToParamQuery();
            //加权限 存的是名称
            if (QmsHelper.GetUserCode() != "super") query = query.AndWhereA("CreatePerson", QmsHelper.GetUserName()).OrWhereB("FileContent_IsPublic", 1);
            var result = service.GetDynamicListWithPaging(query);
            return result;
        }
        /// <summary>
        /// 编辑明细页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dynamic GetEditMaster(string id)
        {
            q_FileContent obj = new q_FileContentService().GetModel(ParamQuery.Instance().AndWhere("FileContent_FileBh", id));
            return new
            {
                form = obj,
                scrollKeys = new q_FileContentService().ScrollKeys("FileContent_FileBh", id.ToString())
            };
        }
        // 地址：GET api/qms/Ldphbz/getdetail
        public dynamic GetDetail(string id)
        {
            var query = RequestWrapper
               .InstanceFromRequest()
               .SetRequestData("FileAttachment_FileBh", id)
               .LoadSettingXmlString(@"
                <settings defaultOrderBy='FileAttachment_RowId'>
                    <select>
                        A.*
                    </select>
                    <from>
                        q_FileAttachment A
                    </from>
                    <where>
                        <field name='FileAttachment_FileBh' cp='equal'></field>
                    </where>
                </settings>");

            var pQuery = query.ToParamQuery();
            var result = new q_FileAttachmentService().GetDynamicListWithPaging(pQuery);
            return result;

        }
        /// <summary>
        /// 得到类型列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// 


        public dynamic GetFileTypes(RequestWrapper request)
        {
            request.LoadSettingXmlString(@"
           <settings defaultOrderBy='FileType_Bh'>
               <where defaultIgnoreEmpty='true'>
                    <field name='FileType_Lb'  cp='equal'></field>
                    <field name='FileType_Bh'  cp='equal'></field>
                    <field name='FileType_Mc'  cp='like' ></field>
                </where>
            </settings>
            ");
            ParamQuery query = request.ToParamQuery();
            if (QmsHelper.GetUserCode() != "super") //判断编码是否为管理员
                query = query.AndWhereA("FileType_UserCode", QmsHelper.GetUserCode()).OrWhereB("FileType_IsPublic", true);
            var result = new q_FileTypeService().GetDynamicList(query);
            return result;
        }

        /// <summary>
        /// 树形参数(queryparams传不过来）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dynamic GetFileTypes2(string id)
        {
            ParamQuery query = new ParamQuery();
            query = query.AndWhere("FileType_Lb", id);
            if (QmsHelper.GetUserCode() != "super") //判断编码是否为管理员
            {
                query = query.AndWhereA("FileType_UserCode", QmsHelper.GetUserCode()).OrWhereB("FileType_IsPublic", true);

            }
            var result = new q_FileTypeService().GetDynamicList(query);
            return result;
        }


        public string GetNewCode()
        {
            //var service = new mms_materialService();
            //return service.GetNewMaterialCode(id);
            return new q_FileContentService().GetNewKey("FileContent_FileBh", "dateplus");
        }

        /// <summary>
        /// 文件类型编号
        /// </summary>
        /// <returns></returns>
        public string GetNewTypeCode()
        {
            return new q_FileTypeService().GetNewKey("FileType_Bh", "maxplus");
        }


        public string GetNewRowId(int id, string BillNo)
        {
            string rowId = new q_FileAttachmentService().GetNewKey("FileAttachment_RowId", "maxplus", id, ParamQuery.Instance().AndWhere("FileAttachment_FileBh", BillNo));
            return rowId;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="data"></param>
        [System.Web.Http.HttpPost]
        public void Edit(dynamic data)
        {
            var formWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>{0}</table>
                <where><field name='FileContent_FileBh' cp='equal'></field></where>
            </settings>", typeof(q_FileContent).Name);

            var listWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>{0}</table>
                <where>
                    <field name='FileAttachment_FileBh' cp='equal'></field>
                    <field name='FileAttachment_RowId'  cp='equal'></field>
                </where>
            </settings>", typeof(q_FileAttachment).Name);

            var result = new q_FileContentService().Edit(formWrapper, listWrapper, data);

        }


        /// <summary>
        /// 删除文件类型 
        /// </summary>
        /// <param name="id"></param>
        public void DeleteTypeCode(string id)
        {
            //判断是否已经使用
            if (new q_FileContentService().GetModelList(new ParamQuery().AndWhere("FileContent_TypeBh", id)).Count > 0)
            {
                PacmHelper.ThrowHttpExceptionWhen(true, "删除文件分类失败[FileContent_TypeBh={0}]，该文件类型已经被使用！", id);
            }
            var result = new q_FileTypeService().Delete(ParamDelete.Instance().AndWhere("FileType_Bh", id));
            PacmHelper.ThrowHttpExceptionWhen(result <= 0, "删除文件分类失败[FileType_Bh={0}]，请重试或联系管理员！", id);
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="id"></param>
        public void Publish(string id)
        {
            int result = 0;
            var mObj = new q_FileContentService().GetModel(new ParamQuery().AndWhere("FileContent_FileBh", id));
            if (mObj != null)
            {
                //判断是否公开文档
                if (mObj.FileContent_IsPublic == 0)
                {
                    PacmHelper.ThrowHttpExceptionWhen(true, "单据发布失败[FielContendId={0}]，非公开文档、不允许发布！", id);
                }
                //888,999
                string[] arrUserCode = mObj.FileContent_UserCode.Split(',');
                if (arrUserCode.Length > 0)
                {
                    foreach (string userCode in arrUserCode)
                    {
                        result += new q_FileContentUsersService()
                            .Insert(new ParamInsert().Column("UserCode", userCode)
                                                     .Column("FielContendId", mObj.FileContent_FileBh)
                                                     .Column("IsRead", 0)
                                                     .Column("IsDown", 0)
                                                     .Column("CreateTime", DateTime.Now)
                                                     .Column("PublishUser", QmsHelper.GetUserName()));
                    }
                }
                if (result > 0)
                {
                    //更新发布状态
                    result += new q_FileContentService().Update(new ParamUpdate().Column("ApproveState", "passed")
                                                                        .Column("ApproveDate", DateTime.Now)
                                                                        .Column("ApprovePerson", QmsHelper.GetUserName())
                                                                        .AndWhere("FileContent_FileBh", id));
                }
            }
            PacmHelper.ThrowHttpExceptionWhen(result <= 2, "单据发布失败[FielContendId={0}]，请重试或联系管理员！", id);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void Delete(string id)
        {
            //判断是否有附件
            if (new q_FileAttachmentService().GetModelList(new ParamQuery().AndWhere("FileAttachment_FileBh", id)).Count > 0)
            {
                PacmHelper.ThrowHttpExceptionWhen(true, "单据删除失败[FileAttachment_FileBh={0}]，请先删除附件！", id);
            }
            var result = new q_FileContentService().Delete(ParamDelete.Instance().AndWhere("FileContent_FileBh", id));
            PacmHelper.ThrowHttpExceptionWhen(result <= 0, "单据删除失败[FileAttachment_FileBh={0}]，请重试或联系管理员！", id);
        }

        [System.Web.Http.HttpPost]
        public void EditFileType(dynamic data)
        {
            var listWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>q_FileType</table>
                <where>
                    <field name='FileType_Bh' cp='equal'></field>
                </where>
            </settings>
            ");
            var service = new q_FileTypeService();
            var result = service.Edit(null, listWrapper, data);

        }


        /// <summary>
        /// 上传
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public dynamic postfile()
        {
            // 设置上传目录
            // var provider = new MultipartFormDataStreamProvider(@"D:\");
            // 接收数据，并保存文件
            // Request.Content.ReadAsMultipartAsync(provider);
            string id = string.Empty;
            string filePath = "";
            string fileType = "";
            string fullfilePath = "";
            try
            {
                var context = HttpContext.Current;
                var request = context.Request;
                //得到文档编号
                id = request.Params["Id"];
                //保存文件
                var postFile = request.Files[0];
                string uploadPath = HttpContext.Current.Server.MapPath("~/Upload/");
                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);
                filePath = postFile.FileName.Substring(postFile.FileName.LastIndexOf("\\") + 1);
                fileType = filePath.Substring(filePath.LastIndexOf("."));
                filePath = filePath.Substring(0, filePath.LastIndexOf("."));
                fullfilePath = uploadPath + filePath + DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond + fileType;
                //存储文件
                request.Files[0].SaveAs(fullfilePath);

                //E:\嘉润电解铝管控一体化-程序\JwkjPacmWeb\JwWeb\Jw.Web\Upload\众和设备管理项目开发计划说明书20141207125117150.docx
                fullfilePath = fullfilePath.Substring(fullfilePath.LastIndexOf("\\") + 1);

                ////把文件转成流存储到数据库
                //Stream stream = request.Files[0].InputStream;
                //byte[] bytes = new byte[stream.Length];
                //stream.Read(bytes, 0, bytes.Length);
                //// 设置当前流的位置为流的开始
                //stream.Seek(0, SeekOrigin.Begin);
                //stream.Close();

                //var service = new q_FileAttachmentService();
                //删除该记录下同名的文件
                //int i = service.Delete(new ParamDelete().AndWhere("FileAttachment_FileBh", id));//.AndWhere("FileAttachment_FullName", filePath));
                //service2.Update(new ParamUpdate().Column("FileContent_Fjsl", 0).AndWhere("FileContent_FileBh", id));



                //string rowId = service.GetNewKey("FileAttachment_RowId", "max", 1, new ParamQuery().AndWhere("FileAttachment_FileBh", id));
                //string sPath = fullfilePath.Substring(uploadPath.Length, fullfilePath.Length - uploadPath.Length);
                //int i = service.Insert(new ParamInsert()
                //     .Column("FileAttachment_FileBh", id)
                //     .Column("FileAttachment_RowId", rowId)
                //     .Column("FileAttachment_Path", sPath)
                //     .Column("FileAttachment_FullName", filePath));

                //更新附件编号

                // service2.Update(new ParamUpdate().Column("FileContent_Fjsl", 1).AndWhere("FileContent_FileBh", id));
                //
            }
            catch (System.Exception e)
            {
                var o = new { success = false, message = e.Message, filepath = fullfilePath, filetype = fileType };
                return new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(o), System.Text.Encoding.UTF8, "text/html") };
            }

            //返回前台
            //return new { success = true, message = "导入成功!" };
            var obss = new { success = true, message = "导入成功!", filepath = fullfilePath, filetype = fileType };
            //以下这种方式返回值 ，FireFox下不报错。 "{\"success\":true,\"message\":\"保存成功！\"}"
            var resp = new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(obss), System.Text.Encoding.UTF8, "text/html") };
            return resp;
        }


    }
}
